package com.example.app3_1;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import java.util.List;

public class HomeFragment extends Fragment {
    private static final String TAG = "HomeFragment";
    private static final String ARG_INTEREST = "interest";
    private String interest;

    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private TextView tvErrorMessage;
    private TextView tvRecommendation;
    private UserAdapter userAdapter;
    private UserViewModel userViewModel;

    // 网络状态跟踪
    private boolean isNetworkAvailable = true;

    public static HomeFragment newInstance(String interest) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_INTEREST, interest);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            interest = getArguments().getString(ARG_INTEREST);
        }

        // 初始化 ViewModel
        userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        initViews(view);
        setupRecyclerView();
        setupObservers();

        // 首次进入时加载数据
        loadUsers();

        return view;
    }

    private void initViews(View view) {
        recyclerView = view.findViewById(R.id.recycler_view);
        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);
        tvErrorMessage = view.findViewById(R.id.tv_error_message);
        tvRecommendation = view.findViewById(R.id.tv_recommendation);

        // 设置推荐文本
        updateRecommendationText();

        // 设置下拉刷新
        swipeRefreshLayout.setOnRefreshListener(() -> {
            loadUsers();
        });

        Log.d(TAG, "视图初始化完成");
    }

    private void setupRecyclerView() {
        userAdapter = new UserAdapter(null);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(userAdapter);
    }

    private void setupObservers() {
        // 观察用户数据
        userViewModel.getUserLiveData().observe(getViewLifecycleOwner(), users -> {
            swipeRefreshLayout.setRefreshing(false);
            if (users != null && !users.isEmpty()) {
                showUserList();
                userAdapter.updateUsers(users);
                Log.d(TAG, "成功显示用户列表，数量: " + users.size());
            } else {
                // 只有在网络不可用或确实没有数据时才显示错误
                if (isNetworkAvailable) {
                    showError("暂无用户数据", false);
                    Log.d(TAG, "服务器返回空数据");
                } else {
                    showError("网络连接失败，请检查网络设置", true);
                    Log.d(TAG, "网络不可用，显示网络错误");
                }
            }
        });

        // 观察错误信息
        userViewModel.getErrorMessage().observe(getViewLifecycleOwner(), errorMessage -> {
            swipeRefreshLayout.setRefreshing(false);
            if (errorMessage != null) {
                // 根据错误类型决定显示方式
                boolean isNetworkError = errorMessage.contains("网络连接失败") ||
                        errorMessage.contains("请求失败");
                showError(errorMessage, isNetworkError);

                // 记录错误日志便于调试
                Log.e(TAG, "数据加载失败: " + errorMessage);
            }
        });
    }

    private void loadUsers() {
        Log.d(TAG, "开始加载用户数据，网络状态: " + (isNetworkAvailable ? "可用" : "不可用"));

        if (!isNetworkAvailable) {
            // 网络不可用时直接显示错误，不发起请求
            showError("网络连接失败，请检查网络设置", true);
            swipeRefreshLayout.setRefreshing(false);
            return;
        }

        swipeRefreshLayout.setRefreshing(true);
        userViewModel.loadUsers();
    }

    private void showUserList() {
        recyclerView.setVisibility(View.VISIBLE);
        tvErrorMessage.setVisibility(View.GONE);
        Log.d(TAG, "显示用户列表");
    }

    private void showError(String message, boolean isNetworkError) {
        recyclerView.setVisibility(View.GONE);
        tvErrorMessage.setVisibility(View.VISIBLE);
        tvErrorMessage.setText(message);
        if (isNetworkError) {
            tvErrorMessage.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
        } else {
            tvErrorMessage.setTextColor(getResources().getColor(android.R.color.darker_gray));
        }
        Log.d(TAG, "显示错误信息: " + message);
    }

    /**
     * 更新推荐文本
     */
    private void updateRecommendationText() {
        if (tvRecommendation != null) {
            if (interest != null && !interest.isEmpty() && !interest.equals("未选择")) {
                tvRecommendation.setText("根据您的兴趣【" + interest + "】，推荐内容如下");
            } else {
                tvRecommendation.setText("推荐内容如下");
            }
        }
    }

    /**
     * 更新网络状态
     */
    public void updateNetworkStatus(boolean available) {
        Log.d(TAG, "网络状态更新: " + (available ? "可用" : "不可用"));
        this.isNetworkAvailable = available;
        // 如果网络恢复，可以尝试自动重新加载
        if (available) {
            loadUsers();
        } else {
            // 网络断开，显示网络错误
            showError("网络连接失败，请检查网络设置", true);
        }
    }

    /**
     * 更新兴趣 - 修复空指针问题
     */
    public void updateInterest(String newInterest) {
        this.interest = newInterest;
        // 只有在视图存在时才更新UI
        if (tvRecommendation != null && isAdded()) {
            updateRecommendationText();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "HomeFragment onResume");
        // 每次Fragment可见时都更新数据
        if (getActivity() instanceof HomeActivity) {
            String latestInterest = ((HomeActivity) getActivity()).getInterest();
            if (latestInterest != null && !latestInterest.isEmpty()) {
                interest = latestInterest;
                updateRecommendationText();
            }
        }
    }
}